const router = require('koa-router')();
const FormData = require('form-data');
const fs = require('fs');
const { formatDate } = require('../../config/formatDate.js');
const { getToken, UploadFileUrl, Addurl, Updateurl } = require('../../config/databaseapi.js');
// const { getLogo } = require('../../config/filetype.js');
const { getFileSize } = require('../../config/filesize.js');
const { v4: uuidv4 } = require('uuid');
router.post('/uploadpic', async (ctx) => {
	console.log('调用上传帖子封面接口');
	// 接收前端传递过来的文件
	const { file } = ctx.request.files;
    // console.log(file);
    const filePath = file.filepath;                                 //文件在koa服务器临时存储的路径
	const fileName = file.originalFilename;                         //文件名

    const cloudpath = `帖子封面/${file.originalFilename}`;
    const res = await new getToken().posteve1(UploadFileUrl,cloudpath);
    console.log("预上传返回结果",res);

	let formData = new FormData();
	formData.append('key', cloudpath);
	formData.append('Signature', res.authorization);
	formData.append('x-cos-security-token', res.token);
	formData.append('x-cos-meta-fileid', res.cos_file_id);
	formData.append('file', fs.createReadStream(filePath), {
		filename: fileName,
		contentType: 'application/octet-stream'
	});

	const res1 = await new getToken().posteve2(res.url, formData);
    console.log("上传返回结果",res1);
    if(res1){
        ctx.body = {msg:"上传成功",status:1,data:{"pic":res.file_id}}
    }else{
        ctx.body = {msg:"上传失败",status:0}
    }
	// if(res1){
	// 	// 存数据库
	// 	const query = `db.collection("study_materials").add({data:${JSON.stringify(obj)}})`;
	// 	const dbres = await new getToken().posteve(Addurl, query);
		 
	// 	// console.log('添加结果', dbres);
	// 	fs.unlink(filePath,(err)=>{
	// 		if(err){
	// 			console.error('上传文件失败');
	// 		}else{
	// 			console.log('上传文件成功');
	// 		}
	// 	})
	// 	if(dbres.errcode === 0){
	// 		ctx.body = {msg:'文件上传成功,写入数据库成功',status:1}
	// 	}else{
	// 		ctx.body = {msg:'文件上传成功,写入数据库失败',status:0}
	// 	}
	// }else{
	// 	ctx.body = {msg:'文件上传失败',status:0}
	// }
})
module.exports = router.routes()